/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lbim.protocol;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import lbim.client.model.Response;
import org.kxml2.io.KXmlParser;

/**
 *
 * @author Jestan
 */
public class SenderThread extends Thread {

    private ResponseListener responseListener;
    private String server;
    private String message;
    private int messageType;
    private String sid;

    public SenderThread(ResponseListener responseListener, String server, String message, int messageType, String sid) {
        this.responseListener = responseListener;
        this.server = server;
        this.message = message;
        this.messageType = messageType;
        this.sid = sid;
    }

    public void run() {
        sendRequest();
    }

    private void sendRequest() {
        DataOutputStream out = null;
        DataInputStream in = null;
        HttpConnection hc = null;
        byte[] bytes = message.getBytes();

        try {
            System.out.println("[SenderThread] Sending XML message, session id:"+ sid);
            hc = (HttpConnection) Connector.open(server);
            hc.setRequestMethod(HttpConnection.POST);

            hc.setRequestProperty("Request-Type", Integer.toString(messageType));
            hc.setRequestProperty("Session-Id", sid);
            hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            hc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
            
            out = hc.openDataOutputStream();
            out.write(bytes);
            String responseType = hc.getHeaderField("Response-Type");
            String responseCode = hc.getHeaderField("Status");
            String contentLength = hc.getHeaderField("Content-Length");
            in = hc.openDataInputStream();

            responseListener.responseReceived(in, responseType, responseCode, contentLength);
        } catch (Throwable e) {
            System.out.println("[SenderThread] Error while sending the message ");
            e.printStackTrace();

        } finally {
            if (hc != null) {
                try {
                    hc.close();
                } catch (Throwable e) {
                    //do nothing
                }
            }
        }
    }


}
